import React from 'react'
import Topic from './components/Topic'
import List from './components/List'
import Recommend from './components/Recommend'
import Writer from './components/Writer'
import { actionCreators } from './store'
import { connect } from 'react-redux'
import {
    HomeWrapper,
    HomeLeft,
    HomeRight,
    BackTop
} from './style'
// PureComponent 内置shouldComponentUpdate 提升性能 但是数据要依赖immutable，否则使用shouldComponentUpdate
class Home extends React.PureComponent { 
    
    handleScrollTop() {
        window.scrollTo(0, 0);
    }

    render() {
        return (
            <HomeWrapper>
                <HomeLeft>
                    <img
                        alt=""
                        className="banner-img"
                        src="http://upload-images.jianshu.io/upload_images/10295326-b7d6641a66c7fafc.png?imageMogr2/auto-orient/strip|imageView2/2/w/524/format/webp"
                    />
                    <Topic/>
                    <List/>
                </HomeLeft>
                <HomeRight>
                    <Recommend/>
                    <Writer/>
                </HomeRight>
                {this.props.showScroll ? <BackTop onClick={this.handleScrollTop}>回到顶部</BackTop> : ''}
                
            </HomeWrapper>
        )
    }

    componentDidMount() {
        this.props.changeHomeData(actionCreators.getMoreList())
        this.bindEvents()
    }

    componentWillUnmount() {
        window.removeEventListener('scroll', this.props.chanegScrollTopShow)
    }

    bindEvents() {
        window.addEventListener('scroll', this.props.chanegScrollTopShow)
    }
}

const mapState = (state) => ({
    showScroll: state.getIn(['home','showScroll'])
})

const mapDisPatch = (dispatch) => ({
    changeHomeData() {
        dispatch(actionCreators.getHomeInfo())
    },
    chanegScrollTopShow(e) {
        if (document.documentElement.scrollTop > 300) {
            dispatch(actionCreators.toggleTopShow(true))
        } else {
            dispatch(actionCreators.toggleTopShow(false))
        }
    }
})

export default connect( mapState, mapDisPatch )(Home)